<template>
  <div class="exam-composer">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <h1>组卷与考试安排</h1>
        <p>创建试卷并安排考试</p>
      </div>
      <div class="header-right">
        <el-button @click="saveDraft">
          <i class="fas fa-save"></i>
          保存草稿
        </el-button>
        <el-button type="primary" @click="publishExam">
          <i class="fas fa-paper-plane"></i>
          发布考试
        </el-button>
      </div>
    </div>

    <div class="composer-content">
      <!-- 左侧：题库管理（跨越两行） -->
      <div class="left-column">
        <div class="panel-card question-bank-card">
          <div class="card-header">
            <h3><i class="fas fa-database"></i> 题库管理</h3>
            <span class="question-count">找到 {{ questionList.length }} 道题目</span>
          </div>
          <div class="card-body">
            <!-- 题库筛选 -->
            <div class="filter-section">
              <div class="filter-row">
                <div class="filter-group">
                  <label>课程选择</label>
                  <el-select
                    v-model="questionFilter.courseId"
                    placeholder="请选择课程"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="course in courses"
                      :key="course.courseId"
                      :label="course.courseName"
                      :value="course.courseId"
                    />
                  </el-select>
                </div>
                <div class="filter-group">
                  <label>题型选择</label>
                  <div class="checkbox-group">
                    <el-checkbox-group v-model="questionFilter.types">
                      <el-checkbox label="single_choice">单选题</el-checkbox>
                      <el-checkbox label="multiple_choice">多选题</el-checkbox>
                      <el-checkbox label="fill_in">填空题</el-checkbox>
                      <el-checkbox label="subjective">主观题</el-checkbox>
                      <el-checkbox label="programming">编程题</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>
                <div class="filter-group">
                  <label>难度选择</label>
                  <div class="checkbox-group">
                    <el-checkbox-group v-model="questionFilter.difficulties">
                      <el-checkbox label="easy">简单</el-checkbox>
                      <el-checkbox label="medium">中等</el-checkbox>
                      <el-checkbox label="hard">困难</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>
              </div>
              <div class="filter-row">
                <div class="filter-group full-width">
                  <label>关键字搜索</label>
                  <el-input
                    v-model="questionFilter.keyword"
                    placeholder="请输入题目关键字"
                    clearable
                  >
                    <template #prefix>
                      <i class="fas fa-search"></i>
                    </template>
                  </el-input>
                </div>
              </div>
              <div class="filter-actions">
                <el-button @click="resetFilter">重置</el-button>
                <el-button type="primary" @click="searchQuestions">
                  <i class="fas fa-search"></i>
                  查询题目
                </el-button>
              </div>
            </div>
            
            <!-- 题目列表 -->
            <div class="question-table-container">
              <el-table
                :data="questionList"
                height="600"
                v-loading="questionLoading"
              >
                <el-table-column prop="content" label="题目内容" min-width="200">
                  <template #default="{ row }">
                    <div class="question-content" v-html="row.content"></div>
                  </template>
                </el-table-column>
                <el-table-column prop="questionType" label="题型" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getQuestionTypeColor(row.questionType)" size="small">
                      {{ getQuestionTypeText(row.questionType) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="difficulty" label="难度" width="80">
                  <template #default="{ row }">
                    <el-tag :type="getDifficultyColor(row.difficulty)" size="small">
                      {{ getDifficultyText(row.difficulty) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="subject" label="科目" width="100" />
                <el-table-column label="操作" width="120">
                  <template #default="{ row }">
                    <el-button
                      type="primary"
                      size="small"
                      @click="addQuestion(row)"
                      :disabled="isQuestionSelected(row.questionId)"
                    >
                      {{ isQuestionSelected(row.questionId) ? '已添加' : '添加' }}
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="questionPagination.page"
                v-model:page-size="questionPagination.size"
                :page-sizes="[10, 20, 50]"
                :total="questionPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：两行布局 -->
      <div class="right-column">
        <!-- 第一行：试卷基本信息 -->
        <div class="panel-card">
          <div class="card-header">
            <h3><i class="fas fa-file-alt"></i> 试卷基本信息</h3>
          </div>
          <div class="card-body">
            <el-form :model="examForm" :rules="examRules" ref="examFormRef" label-width="100px">
              <div class="form-row">
                <el-form-item label="试卷名称" prop="title" class="form-item-half">
                  <el-input v-model="examForm.title" placeholder="请输入试卷名称" />
                </el-form-item>
                <el-form-item label="所属课程" prop="courseId" class="form-item-half">
                  <el-select v-model="examForm.courseId" placeholder="请选择课程" style="width: 100%">
                    <el-option
                      v-for="course in courses"
                      :key="course.courseId"
                      :label="course.courseName"
                      :value="course.courseId"
                    />
                  </el-select>
                </el-form-item>
              </div>
              <div class="form-row">
                <el-form-item label="考试时长" prop="durationMinutes" class="form-item-half">
                  <el-input-number
                    v-model="examForm.durationMinutes"
                    :min="1"
                    :max="300"
                    placeholder="分钟"
                    style="width: 100%"
                    @change="calculateEndTime"
                  />
                </el-form-item>
                <el-form-item label="试卷总分" class="form-item-half">
                  <el-input :value="totalScore" readonly placeholder="自动计算" />
                </el-form-item>
              </div>
              <el-form-item label="试卷描述">
                <el-input
                  v-model="examForm.description"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入试卷描述"
                />
              </el-form-item>
            </el-form>
          </div>
        </div>

        <!-- 第二行：考试安排 -->
        <div class="panel-card">
          <div class="card-header">
            <h3><i class="fas fa-calendar-alt"></i> 考试安排</h3>
          </div>
          <div class="card-body">
            <el-form :model="scheduleForm" :rules="scheduleRules" ref="scheduleFormRef" label-width="120px">
              <el-form-item label="选择班级/小组" prop="groupIds">
                <el-select
                  v-model="scheduleForm.groupIds"
                  multiple
                  placeholder="请选择班级或小组"
                  style="width: 100%"
                >
                  <el-option
                    v-for="group in userGroups"
                    :key="group.groupId"
                    :label="group.groupName"
                    :value="group.groupId"
                  />
                </el-select>
              </el-form-item>
              <div class="form-row">
                <el-form-item label="开始时间" prop="startTime" class="form-item-half">
                  <el-date-picker
                    v-model="scheduleForm.startTime"
                    type="datetime"
                    placeholder="选择开始时间"
                    style="width: 100%"
                    @change="calculateEndTime"
                  />
                </el-form-item>
                <el-form-item label="结束时间" prop="endTime" class="form-item-half">
                  <el-date-picker
                    v-model="scheduleForm.endTime"
                    type="datetime"
                    placeholder="自动计算或手动选择"
                    style="width: 100%"
                  />
                </el-form-item>
              </div>
              <el-form-item label="考试说明">
                <el-input
                  v-model="scheduleForm.instructions"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入考试说明"
                />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>

      <!-- 右下角：已选题目列表 -->
      <div class="bottom-right-column">
        <div class="panel-card">
          <div class="card-header">
            <h3><i class="fas fa-check-square"></i> 已选题目列表</h3>
            <div class="selected-stats">
              题目数量: <span class="stat-number">{{ selectedQuestions.length }}</span> 题 |
              总分: <span class="stat-number">{{ totalScore }}</span> 分
            </div>
          </div>
          <div class="card-body">
            <div class="selected-questions-container">
              <div v-if="selectedQuestions.length === 0" class="empty-state">
                <i class="fas fa-clipboard-list"></i>
                <p>尚未选择题目，请从左侧题目列表中添加</p>
              </div>
              <div v-else class="selected-questions-list">
                <div
                  v-for="(question, index) in selectedQuestions"
                  :key="question.questionId"
                  class="selected-question-item"
                >
                  <div class="question-header">
                    <span class="question-number">{{ index + 1 }}.</span>
                    <el-tag :type="getQuestionTypeColor(question.questionType)" size="small">
                      {{ getQuestionTypeText(question.questionType) }}
                    </el-tag>
                    <el-tag :type="getDifficultyColor(question.difficulty)" size="small">
                      {{ getDifficultyText(question.difficulty) }}
                    </el-tag>
                    <div class="question-actions">
                      <el-input-number
                        v-model="question.score"
                        :min="1"
                        :max="100"
                        size="small"
                        @change="updateTotalScore"
                      />
                      <span class="score-label">分</span>
                      <el-button
                        type="danger"
                        size="small"
                        @click="removeQuestion(index)"
                      >
                        <i class="fas fa-trash"></i>
                      </el-button>
                    </div>
                  </div>
                  <div class="question-content" v-html="question.content"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listMyQuestions, listQuestionsByCourse } from '@/api/questions/questions'
import { getMyCourses } from '@/api/course-management'
import { getUserGroups } from '@/api/rbac/userGroups'
import { createExam } from '@/api/exam/exams'
import { createExamAssignment } from '@/api/exam/examAssignments'

// 表单引用
const examFormRef = ref()
const scheduleFormRef = ref()

// 课程列表
const courses = ref([])

// 用户组列表
const userGroups = ref([])

// 试卷表单
const examForm = reactive({
  title: '',
  description: '',
  courseId: null,
  durationMinutes: 120
})

// 试卷表单验证规则
const examRules = {
  title: [{ required: true, message: '请输入试卷名称', trigger: 'blur' }],
  courseId: [{ required: true, message: '请选择课程', trigger: 'change' }],
  durationMinutes: [{ required: true, message: '请输入考试时长', trigger: 'blur' }]
}

// 考试安排表单
const scheduleForm = reactive({
  groupIds: [],
  startTime: null,
  endTime: null,
  instructions: ''
})

// 考试安排表单验证规则
const scheduleRules = {
  groupIds: [{ required: true, message: '请选择班级或小组', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
}

// 题目筛选条件
const questionFilter = reactive({
  courseId: null,
  types: [],
  difficulties: [],
  keyword: ''
})

// 题目列表
const questionList = ref([])
const questionLoading = ref(false)

// 分页信息
const questionPagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 已选题目列表
const selectedQuestions = ref([])

// 计算总分
const totalScore = computed(() => {
  return selectedQuestions.value.reduce((sum, question) => sum + (question.score || 0), 0)
})

// 获取题型颜色
const getQuestionTypeColor = (type) => {
  const colors = {
    single_choice: 'primary',
    multiple_choice: 'success',
    fill_in: 'warning',
    subjective: 'info',
    programming: 'danger'
  }
  return colors[type] || 'info'
}

// 获取题型文本
const getQuestionTypeText = (type) => {
  const texts = {
    single_choice: '单选',
    multiple_choice: '多选',
    fill_in: '填空',
    subjective: '主观',
    programming: '编程'
  }
  return texts[type] || type
}

// 获取难度颜色
const getDifficultyColor = (difficulty) => {
  const colors = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return colors[difficulty] || 'info'
}

// 获取难度文本
const getDifficultyText = (difficulty) => {
  const texts = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return texts[difficulty] || difficulty
}

// 判断题目是否已选择
const isQuestionSelected = (questionId) => {
  return selectedQuestions.value.some(q => q.questionId === questionId)
}

// 添加题目
const addQuestion = (question) => {
  if (isQuestionSelected(question.questionId)) {
    return
  }
  
  // 检查题目类型是否在筛选条件中
  if (questionFilter.types.length > 0 && !questionFilter.types.includes(question.questionType)) {
    ElMessage.warning('该题目类型未在筛选条件中，无法添加')
    return
  }
  
  // 检查题目难度是否在筛选条件中
  if (questionFilter.difficulties.length > 0 && !questionFilter.difficulties.includes(question.difficulty)) {
    ElMessage.warning('该题目难度未在筛选条件中，无法添加')
    return
  }
  
  const questionWithScore = {
    ...question,
    score: 5 // 默认分值
  }
  
  selectedQuestions.value.push(questionWithScore)
  ElMessage.success('题目添加成功')
}

// 移除题目
const removeQuestion = (index) => {
  selectedQuestions.value.splice(index, 1)
  ElMessage.success('题目移除成功')
}

// 更新总分
const updateTotalScore = () => {
  // 触发计算属性重新计算
}

// 重置筛选条件
const resetFilter = () => {
  questionFilter.courseId = null
  questionFilter.types = []
  questionFilter.difficulties = []
  questionFilter.keyword = ''
  searchQuestions()
}

// 搜索题目
const searchQuestions = async () => {
  questionLoading.value = true
  try {
    let response
    // 如果选择了课程，则根据课程ID获取题目，否则获取我的所有题目
    if (questionFilter.courseId) {
      response = await listQuestionsByCourse(questionFilter.courseId)
    } else {
      response = await listMyQuestions()
    }
    
    if (response && response.code === 200 && response.data) {
      let filteredQuestions = response.data
      
      // 前端筛选逻辑
      if (questionFilter.types.length > 0) {
        filteredQuestions = filteredQuestions.filter(q => 
          questionFilter.types.includes(q.questionType)
        )
      }
      
      if (questionFilter.difficulties.length > 0) {
        filteredQuestions = filteredQuestions.filter(q => 
          questionFilter.difficulties.includes(q.difficulty)
        )
      }
      
      if (questionFilter.keyword) {
        filteredQuestions = filteredQuestions.filter(q => 
          q.content.toLowerCase().includes(questionFilter.keyword.toLowerCase())
        )
      }
      
      // 分页处理
      const startIndex = (questionPagination.page - 1) * questionPagination.size
      const endIndex = startIndex + questionPagination.size
      
      questionList.value = filteredQuestions.slice(startIndex, endIndex)
      questionPagination.total = filteredQuestions.length
    } else {
      questionList.value = []
      questionPagination.total = 0
    }
  } catch (error) {
    console.warn('获取题目列表失败，可能是后端接口未实现:', error)
    questionList.value = []
    questionPagination.total = 0
    if (error.message && !error.message.includes('401') && !error.message.includes('无效的会话')) {
      ElMessage.warning('题目列表暂时无法加载，请稍后重试')
    }
  } finally {
    questionLoading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  questionPagination.size = size
  searchQuestions()
}

// 当前页改变
const handleCurrentChange = (page) => {
  questionPagination.page = page
  searchQuestions()
}

// 自动计算结束时间
const calculateEndTime = () => {
  if (scheduleForm.startTime && examForm.durationMinutes) {
    const startTime = new Date(scheduleForm.startTime)
    const endTime = new Date(startTime.getTime() + examForm.durationMinutes * 60 * 1000)
    scheduleForm.endTime = endTime
  }
}

// 获取课程列表
const loadCourses = async () => {
  try {
    const response = await getMyCourses()
    if (response && response.code === 200 && response.data) {
      courses.value = response.data
    } else {
      courses.value = []
    }
  } catch (error) {
    console.warn('获取课程列表失败，可能是后端接口未实现:', error)
    courses.value = []
    if (error.message && !error.message.includes('401') && !error.message.includes('无效的会话')) {
      ElMessage.warning('课程列表暂时无法加载，请稍后重试')
    }
  }
}

// 获取用户组列表
const loadUserGroups = async () => {
  try {
    const response = await getUserGroups()
    if (response.data) {
      userGroups.value = response.data.records || response.data
    }
  } catch (error) {
    ElMessage.error('获取班级列表失败')
    console.error(error)
  }
}

// 保存草稿
const saveDraft = async () => {
  try {
    // 验证基本信息
    await examFormRef.value.validate()
    
    if (selectedQuestions.value.length === 0) {
      ElMessage.warning('请至少选择一道题目')
      return
    }
    
    // 创建试卷（草稿状态，不设置开始和结束时间）
    const examData = {
      title: examForm.title,
      description: examForm.description,
      durationMinutes: examForm.durationMinutes,
      courseId: examForm.courseId,
      questions: selectedQuestions.value.map((q, index) => ({
        questionId: q.questionId,
        questionOrder: index + 1,
        score: q.score || 5  // 添加分数字段，默认5分
      }))
    }
    
    console.log('保存草稿数据:', examData)
    
    const examResponse = await createExam(examData)
    console.log('草稿保存响应:', examResponse)
    
    if (examResponse && examResponse.code === 200) {
      ElMessage.success('草稿保存成功')
    } else {
      throw new Error('草稿保存失败：' + (examResponse?.message || '未知错误'))
    }
  } catch (error) {
    console.error('保存草稿失败:', error)
    ElMessage.error('保存草稿失败：' + (error.message || '未知错误'))
  }
}

// 发布考试
const publishExam = async () => {
  try {
    // 验证试卷信息
    await examFormRef.value.validate()
    
    // 验证考试安排
    await scheduleFormRef.value.validate()
    
    if (selectedQuestions.value.length === 0) {
      ElMessage.warning('请至少选择一道题目')
      return
    }
    
    await ElMessageBox.confirm('确认发布考试吗？发布后将无法修改试卷内容。', '确认发布', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 格式化时间为后端需要的格式（yyyy-MM-dd HH:mm:ss）
     const formatTimeForBackend = (dateTime) => {
       if (!dateTime) return null
       const date = new Date(dateTime)
       const year = date.getFullYear()
       const month = String(date.getMonth() + 1).padStart(2, '0')
       const day = String(date.getDate()).padStart(2, '0')
       const hours = String(date.getHours()).padStart(2, '0')
       const minutes = String(date.getMinutes()).padStart(2, '0')
       const seconds = String(date.getSeconds()).padStart(2, '0')
       return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}` // 格式：yyyy-MM-dd HH:mm:ss
     }
    
    // 创建试卷
    const examData = {
      title: examForm.title,
      description: examForm.description,
      startTime: formatTimeForBackend(scheduleForm.startTime),
      endTime: formatTimeForBackend(scheduleForm.endTime),
      durationMinutes: examForm.durationMinutes,
      courseId: examForm.courseId,
      questions: selectedQuestions.value.map((q, index) => ({
        questionId: q.questionId,
        questionOrder: index + 1,
        score: q.score || 5  // 添加分数字段，默认5分
      }))
    }
    
    console.log('创建试卷数据:', examData)
    
    // 第一步：创建试卷
    const examResponse = await createExam(examData)
    console.log('试卷创建响应:', examResponse)
    
    // 检查试卷创建是否成功
    if (!examResponse || examResponse.code !== 200 || !examResponse.data) {
      throw new Error('试卷创建失败：' + (examResponse?.message || '未知错误'))
    }
    
    const examId = examResponse.data
    console.log('获取到的试卷ID:', examId)
    
    // 第二步：创建考试安排（确保试卷创建成功后再执行）
    const assignmentPromises = []
    for (const groupId of scheduleForm.groupIds) {
      const assignmentData = {
        examId,
        groupId,
        startTime: formatTimeForBackend(scheduleForm.startTime),
        endTime: formatTimeForBackend(scheduleForm.endTime),
        instructions: scheduleForm.instructions
      }
      
      console.log('创建考试安排数据:', assignmentData)
      assignmentPromises.push(createExamAssignment(assignmentData))
    }
    
    // 等待所有考试安排创建完成
    const assignmentResults = await Promise.all(assignmentPromises)
    console.log('考试安排创建结果:', assignmentResults)
    
    ElMessage.success('考试发布成功')
    
    // 重置表单
    resetForms()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('发布考试失败')
      console.error(error)
    }
  }
}

// 重置表单
const resetForms = () => {
  examFormRef.value?.resetFields()
  scheduleFormRef.value?.resetFields()
  selectedQuestions.value = []
  Object.assign(examForm, {
    title: '',
    description: '',
    courseId: null,
    durationMinutes: 120
  })
  Object.assign(scheduleForm, {
    groupIds: [],
    startTime: null,
    endTime: null,
    instructions: ''
  })
}

// 初始化
onMounted(() => {
  loadCourses()
  loadUserGroups()
  searchQuestions()
})
</script>

<style scoped>
.exam-composer {
  padding: 20px;
  margin: 0 40px;
  background-color: #f5f7fa;
  min-height: 100vh;
  overflow-x: hidden; /* 防止水平滚动条 */
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-left p {
  margin: 5px 0 0 0;
  color: #909399;
  font-size: 14px;
}

.composer-content {
  display: grid;
  grid-template-columns: 0.5fr 2fr; /* 左侧0.5份，右侧2份 */
  grid-template-rows: 1fr 1fr; /* 两行等高 */
  gap: 20px;
  min-height: calc(100vh - 160px); /* 最小高度，允许内容超出 */
  overflow: visible; /* 允许内容溢出显示 */
}

.left-column {
  grid-row: 1 / 3; /* 跨越两行 */
  grid-column: 1; /* 第一列 */
}

.right-column {
  grid-row: 1; /* 第一行 */
  grid-column: 2; /* 第二列 */
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.bottom-right-column {
  grid-row: 2; /* 第二行 */
  grid-column: 2; /* 第二列 */
}

.panel-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.card-header {
  background: #ecf5ff;
  padding: 15px 20px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  color: #409eff;
  display: flex;
  align-items: center;
  gap: 8px;
}

.question-count {
  font-size: 14px;
  color: #909399;
}

.selected-stats {
  font-size: 14px;
  color: #606266;
}

.stat-number {
  font-weight: bold;
  color: #409eff;
}

.card-body {
  padding: 20px;
}

.form-row {
  display: flex;
  gap: 20px;
}

.form-item-half {
  flex: 1;
}

.filter-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-row {
  display: flex;
  gap: 20px;
}

.filter-group {
  flex: 1;
}

.filter-group.full-width {
  flex: none;
  width: 100%;
}

.filter-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}

.checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.filter-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.question-bank-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.question-bank-card .card-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.filter-section {
  margin-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 15px;
}

.question-table-container {
  flex: 1;
  overflow: hidden;
  min-height: 0; /* 确保flex子元素可以收缩 */
}

.question-content {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pagination-container {
  padding: 15px 20px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: center;
  flex-shrink: 0; /* 防止分页组件被压缩 */
  background: white;
}

.selected-questions-container {
  height: calc(100% - 60px); /* 减去header高度 */
  overflow-y: auto;
  overflow-x: hidden;
  /* 自定义滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 transparent;
}

.selected-questions-container::-webkit-scrollbar {
  width: 6px;
}

.selected-questions-container::-webkit-scrollbar-track {
  background: transparent;
}

.selected-questions-container::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 3px;
}

.selected-questions-container::-webkit-scrollbar-thumb:hover {
  background-color: #a8a8a8;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #909399;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.3;
}

.selected-questions-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.selected-question-item {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 16px;
  background: #fafafa;
}

.question-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.question-number {
  font-weight: bold;
  color: #409eff;
  min-width: 30px;
}

.question-actions {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 8px;
}

.score-label {
  font-size: 14px;
  color: #606266;
}

.selected-question-item .question-content {
  max-width: none;
  white-space: normal;
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
}

/* 确保所有panel-card填满容器 */
.left-column .panel-card,
.right-column .panel-card,
.bottom-right-column .panel-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.left-column .card-body,
.right-column .card-body,
.bottom-right-column .card-body {
  flex: 1;
  overflow: auto; /* 允许滚动 */
  min-height: 0; /* 确保flex子元素可以收缩 */
}

.right-column .panel-card {
  flex: 1;
}

@media (max-width: 1200px) {
  .composer-content {
    grid-template-columns: 1fr;
    grid-template-rows: auto auto auto;
    height: auto;
  }
  
  .left-column {
    grid-row: 1;
    grid-column: 1;
    min-height: 600px;
  }
  
  .right-column {
    grid-row: 2;
    grid-column: 1;
    min-height: 400px;
  }
  
  .bottom-right-column {
    grid-row: 3;
    grid-column: 1;
    min-height: 400px;
  }
}
</style>